﻿using IRepositoryBll;
using IRepositoryDal;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RepositoryEntity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RepositoryBll
{
    public class ConsumableRecordBll : IConsumableRecordBll
    {
        private IConsumableRecordDal _consumableRecordDal;
        private IConsumableInfoDal _consumableInfoDal;
        private IUserInfoDal _userInfoDal;

        private RepositoryDbContext _dbContext;
        public ConsumableRecordBll(IConsumableRecordDal consumableRecordDal, IConsumableInfoDal consumableInfoDal, IUserInfoDal userInfoDal, RepositoryDbContext dbContext)
        {
            _consumableRecordDal = consumableRecordDal;
            _consumableInfoDal = consumableInfoDal;
            _userInfoDal = userInfoDal;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 添加耗材记录信息
        /// </summary>
        /// <param name="consumableRecord"></param>
        /// <returns></returns>
        public bool AddConsumableRecord(ConsumableRecord consumableRecord)
        {
            return _consumableRecordDal.Add(consumableRecord);
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="consumbleId"></param>
        /// <returns></returns>
        public bool DeleteConsumableRecords(string consumbleId)
        {
            ConsumableRecord consumableRecordId = _consumableRecordDal.GetEntity(consumbleId);
            if (consumbleId != null)
            {
                return _consumableRecordDal.Delete(consumbleId);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取耗材记录集合、分页
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
        /// <param name="consumbleId"></param>
        /// <returns></returns>
        public object GetConsumableRecordListByPage(int page, int limit, out int count, string consumbleId)
        {
            //获取耗材信息集合
            var consumableRecords = _consumableRecordDal.GetEntitiesDb().AsQueryable();

            if (!string.IsNullOrEmpty(consumbleId))
            {
                consumableRecords = consumableRecords.Where(u => u.ConsumbleId == consumbleId);
            }
            //查询出来数据的数量
            count = consumableRecords.Count();
            //连表查询
            var tempList = (from cr in consumableRecords
                            join c in _consumableInfoDal.GetEntitiesDb().Where(c => !c.IsDelete)
                            on cr.ConsumbleId equals c.ID into tempCrC
                            from cc in tempCrC.DefaultIfEmpty()

                            join u in _userInfoDal.GetEntitiesDb().Where(u => !u.IsDelete)
                            on cr.Creator equals u.ID into tempUrC
                            from uu in tempUrC.DefaultIfEmpty()
                            select new
                            {
                                cr.ID,
                                cr.CreateTime,
                                cr.Num,
                                cr.Type,
                                ConsumableName = cc.Name,
                                uu.UserName
                            });
            //分页
            //分页
            tempList = tempList.OrderBy(u => u.CreateTime).Skip((page - 1) * limit).Take(limit);
            var list = tempList.ToList().Select(u => new
            {
                u.UserName,
                u.ConsumableName,
                u.Num,
                Type = u.Type == 1 ? "入库" : "出库",
                u.ID,
                CreateTime = u.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
            });
            return list;


            //获取耗材信息集合
            //var consumableRecord = _consumableRecordDal.GetEntitiesDb().Select(u => new
            //{
            //    u.ID,
            //    u.ConsumbleId,
            //    u.CreateTime,
            //    u.Creator,
            //    u.Num
            //});
            //if (!string.IsNullOrEmpty(consumbleId))
            //{
            //    consumableRecord = consumableRecord.Where(u => u.Creator.Contains(consumbleId));
            //}
            ////统计数据数量
            //count = consumableRecord.Count();



            //consumableRecord = consumableRecord.Skip((page - 1) * limit).Take(limit);
            //var list = consumableRecord.ToList().Select(u =>
            //{
            //    return new
            //    {
            //        u.ID,
            //        u.ConsumbleId,
            //        u.CreateTime,
            //        u.Creator,
            //        u.Num

            //    };
            //});
            //return list;
        }

        /// <summary>
        /// 文件下载 
        /// </summary>
        /// <returns></returns>
        public Stream GetDownloadDatas()
        {
            var datas = (from cr in _consumableRecordDal.GetEntitiesDb()
                         join c in _consumableInfoDal.GetEntitiesDb().Where(c => !c.IsDelete)
                         on cr.ConsumbleId equals c.ID
                         select new
                         {
                             cr.Num,
                             c.Name,
                             cr.CreateTime,
                             cr.Type
                         }).ToList();
            //获取当前目录
            var dPath = Directory.GetCurrentDirectory();
            //文件名
            var fileName = "output.xlsx";
            var filePath = Path.Combine(dPath, fileName);
            //数据流
            FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            //文件管理对象
            IWorkbook workbook = new XSSFWorkbook();
            //创建第一个sheet表格
            ISheet excelSheet = workbook.CreateSheet("Sheet1");

            for (int i = 0; i < datas.Count; i++)
            {
                //创建一行
                IRow row = excelSheet.CreateRow(i);
                //创建一列
                row.CreateCell(0).SetCellValue(datas[i].Name);
                //创建二列
                row.CreateCell(1).SetCellValue(datas[i].Num);
                //创建三列
                string typeStr = datas[i].Type == 1 ? "入库" : "出库";
                row.CreateCell(2).SetCellValue(typeStr);
                //创建四列
                string dataTimeStr = datas[i].CreateTime.ToString("yyyy-mm-dd HH:mm:ss");
                row.CreateCell(3).SetCellValue(dataTimeStr);
            }
            //写入文件流
            workbook.Write(fileStream);
            //读取已写文件
            FileStream resStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            return resStream;

        }


        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="iD"></param>
        public bool Upload(Stream stream, string userInfoId, out string msg)
        {
            msg = "";
            stream.Position = 0;
            XSSFWorkbook xSSFWorkbook = new XSSFWorkbook(stream);
            ISheet sheet = xSSFWorkbook.GetSheetAt(0);
            if (sheet != null)
            {
                using (var transaction = _dbContext.Database.BeginTransaction())
                {
                    
                    var rowLength = sheet.LastRowNum;
                    //添加耗材记录集合
                    List<ConsumableRecord> ConsumableRecords = new List<ConsumableRecord>();
                    //批量修改耗材记录集合
                    List<ConsumableInfo> consumableInfos = new List<ConsumableInfo>();

                    for (int i = 0; i <= rowLength; i++)
                    {
                        //获取第一行
                        IRow row = sheet.GetRow(i);

                        if (row != null)
                        {
                            //列
                            int cellCount = row.LastCellNum;
                            var name = row.Cells[0].ToString();
                            var value = row.Cells[1].ToString();

                            //类型转换
                            int num = 0;
                            int.TryParse(value, out num);

                            //根据耗材名称查询耗材ID
                            var consumableInfo = _consumableInfoDal.GetEntitiesDb().FirstOrDefault(c => c.Name == name);
                            if (consumableInfo != null)
                            {
                                ConsumableRecord consumableRecord = new ConsumableRecord()
                                {
                                    ID = Guid.NewGuid().ToString(),
                                    CreateTime = DateTime.Now,
                                    Type = 1,
                                    Creator = userInfoId,
                                    Num = num,
                                    ConsumbleId = consumableInfo != null ? consumableInfo.ID : ""
                                };
                                //bool isSuccess = _consumableRecordDal.Add(consumableRecord);

                                ConsumableRecords.Add(consumableRecord);

                                //添加耗材数量
                                consumableInfo.Num += num;
                                consumableInfos.Add(consumableInfo);

                                // _consumableInfoDal.Update(consumableInfo);
                               // _consumableInfoDal.Add(consumableInfo);
                            }
                            else
                            {
                                msg = string.Format("{0}商品有误 ，在第{1}行", name, i + 1);
                                transaction.Rollback();
                                if (string.IsNullOrEmpty(msg))
                                {
                                    msg = "数据有误";
                                }
                                return false;
                            }


                        }


                    }
                    int index = _consumableRecordDal.Adds(ConsumableRecords);
                    
                    _consumableInfoDal.Updates(consumableInfos);
                    transaction.Commit();
                    return true;

                }

            }
            else
            {
                return false;
            }

        }
    } 
}
        

        //public void SoftDeleteConsumableRecords(List<string> consumableRecordIds)
        //{
        //    throw new NotImplementedException();
        //}

        //public void SoftDeleteConsumableRecords(List<string> consumableRecordIds)
        //{
        //    //获取耗材记录要删除的耗材记录集合
        //    var deleteConsumableRecords = _consumableRecordDal.GetEntitiesDb().Where(u => consumableRecordIds.Contains(u.ID)).ToList();
        //    DateTime dateTime = DateTime.Now;
        //    foreach (var item in deleteConsumableRecords)
        //    {
        //        item.IsDelete = true;
        //        item.DeleteTime = dateTime;
        //    }
        //    _consumableRecordDal.Updates(deleteConsumableRecords);
        //}
    
